package com.ruoyi.cms.controller.website;

import com.ruoyi.cms.domain.CmsCategory;
import com.ruoyi.cms.dto.CmsCategoryDto;
import com.ruoyi.cms.service.ICmsCategoryService;
import com.ruoyi.common.core.utils.bean.BeanUtils;
import com.ruoyi.common.core.web.controller.BaseController;
import com.ruoyi.common.core.web.domain.AjaxResult;
import com.ruoyi.common.core.web.page.TableDataInfo;
import com.ruoyi.common.log.annotation.Log;
import com.ruoyi.common.log.enums.BusinessType;
import io.swagger.v3.oas.annotations.Operation;
import io.swagger.v3.oas.annotations.tags.Tag;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;

/**
 * 分类Controller
 *
 * @author houyong
 * @date 2025-11-08
 */
@Tag(name = "CmsSiteCategoryController", description = "栏目管理 for web前端")
@RestController
@RequestMapping("cms/website/category")
public class CmsSiteCategoryController extends BaseController {
    @Autowired
    private ICmsCategoryService cmsCategoryService;

    /**
     * 查询分类列表
     */
    @Operation(summary = "分页查询分类列表")
    @GetMapping("/list")
    public TableDataInfo list(CmsCategory cmsCategory) {
        startPage();
        List<CmsCategory> list = cmsCategoryService.selectCmsCategoryList(cmsCategory);
        return getDataTable(list);
    }

    @Operation(summary = "查询所有分类列表")
    @RequestMapping(value = "/all/list", method = {RequestMethod.POST, RequestMethod.GET})
    public AjaxResult allList(CmsCategory cmsCategory) {
        cmsCategory.setDel(0L);
        List<CmsCategory> list = cmsCategoryService.selectCmsCategoryList(cmsCategory);
        List<CmsCategoryDto> dtoList = convertToDtoList(list);
        List<CmsCategoryDto> treeList = buildCategoryTree(dtoList);
        return success(treeList);

    }

    /**
     * 将CmsCategory实体列表转换为CmsCategoryDto对象列表
     *
     * @param categories CmsCategory实体对象列表
     * @return 转换后的CmsCategoryDto对象列表
     */
    // 转换方法
    private List<CmsCategoryDto> convertToDtoList(List<CmsCategory> categories) {
        // 使用Stream API将实体列表映射为DTO列表
        return categories.stream()
                .map(e -> {
                    CmsCategoryDto dto = new CmsCategoryDto();
                    BeanUtils.copyProperties(e, dto);
                    return dto;
                })
                .collect(Collectors.toList());
    }


    /**
     * 构建成树形结构
     *
     * @param categories
     * @return
     */
    private List<CmsCategoryDto> buildCategoryTree(List<CmsCategoryDto> categories) {
        Map<String, CmsCategoryDto> categoryMap = new HashMap<>();
        List<CmsCategoryDto> rootCategories = new ArrayList<>();

        // 建立映射关系：以 id 为 key
        for (CmsCategoryDto category : categories) {
            if (category.getId() != null) {
                categoryMap.put(category.getId(), category);
            }
        }

        // 构建树形结构
        for (CmsCategoryDto category : categories) {
            // 判断是否为根节点：categoryId 为 null
            if (category.getCategoryId() == null || category.getCategoryId().isEmpty()) {
                rootCategories.add(category);
            } else {
                // 查找父节点（通过 categoryId 查找 id 匹配的节点）
                CmsCategoryDto parent = categoryMap.get(category.getCategoryId());
                if (parent != null) {
                    if (parent.getChildren() == null) {
                        parent.setChildren(new ArrayList<>());
                    }
                    parent.getChildren().add(category);
                }
            }
        }

        return rootCategories;
    }


    /**
     * 获取分类详细信息
     */
    @Operation(summary = "获取分类详细信息")
    @GetMapping(value = "/{id}")
    public AjaxResult getInfo(@PathVariable("id") String id) {
        return success(cmsCategoryService.selectCmsCategoryById(id));
    }


    @Operation(summary = "根据父级id查询分类列表")
    @GetMapping(value = "/by/parentId")
    public AjaxResult getInfoByParentId(@RequestParam String id) {
        CmsCategory cmsCategory = new CmsCategory();
        cmsCategory.setCategoryId(id);
        return success(cmsCategoryService.selectCmsCategoryList(cmsCategory));
    }
}
